# 6: TRACE
# 5: VERBOSE
# 4: DEBUG
# 3: INFO
# 2: WARN
# 1: ERROR

toolchain ?=
log ?= 6
cpu ?=
dbg ?= 1
out ?= $(CURDIR)/../build


CC := $(toolchain)g++

AR := $(toolchain)ar

CC_FLAG := -std=c++14 $(cpu) -DLOG_LEVEL=$(log)

AR_FLAG := rcs

LD_FLAG := -shared

FLAG_DEBUG := -O0 -g

FLAG_RELEASE := -O2 -w -DNDEBUG=1

ifeq ($(dbg), 0)
CC_FLAG += $(FLAG_RELEASE)
else
CC_FLAG += $(FLAG_DEBUG)
endif


jlib_static := $(out)/out/libjlib.a
server_app := $(out)/out/proxy-server
client_app := $(out)/out/proxy-client

include_dirs :=
include_dirs += -I$(CURDIR)/..
include_dirs += -I/usr/include
include_dirs += -I/usr/local/include

library_dirs :=
library_dirs += -L/usr/lib
library_dirs += -L/usr/local/lib
library_dirs += -L$(out)/out

dependencies :=
dependencies += -lcrypto
dependencies += -lssl
dependencies += -lpthread

server_headers :=
server_headers += common/factory.h
server_headers += common/console.h
server_headers += common/protocol.h
server_headers += common/codec.h
server_headers += server/config.h
server_headers += server/router.h
server_headers += server/tunnel.h
server_headers += server/server.h

client_headers :=
client_headers += common/factory.h
client_headers += common/console.h
client_headers += common/protocol.h
client_headers += common/codec.h
client_headers += client/config.h
client_headers += client/router.h
client_headers += client/tunnel.h
client_headers += client/client.h

server_sources :=
server_sources += common/factory.cpp
server_sources += common/codec.cpp
server_sources += server/router.cpp
server_sources += server/tunnel.cpp
server_sources += server/server.cpp
server_sources += server/main.cpp

client_sources :=
client_sources += common/factory.cpp
client_sources += common/codec.cpp
client_sources += client/router.cpp
client_sources += client/tunnel.cpp
client_sources += client/client.cpp
client_sources += client/main.cpp


.PHONY : all server client asm

all : server client

server : $(jlib_static) $(server_app)

client : $(jlib_static) $(client_app)

asm : $(sources:%.cpp=$(out)/obj/proxy/%.s)

$(jlib_static) :
	make -C $(CURDIR)/../jlib static toolchain=$(toolchain) log=$(log) cpu=$(cpu) dbg=$(dbg) out=$(out)

$(server_app) : $(server_sources:%.cpp=$(out)/obj/proxy/%.o)
	@mkdir -p $(@D)
	$(CC) -o $@ $^ $(library_dirs) -Wl,-Bstatic -ljlib -Wl,-Bdynamic $(dependencies)

$(client_app) : $(client_sources:%.cpp=$(out)/obj/proxy/%.o)
	@mkdir -p $(@D)
	$(CC) -o $@ $^ $(library_dirs) -Wl,-Bstatic -ljlib -Wl,-Bdynamic $(dependencies)

$(out)/obj/proxy/%.o : %.cpp
	@mkdir -p $(@D)
	$(CC) -c $(CC_FLAG) -o $@ $^ $(include_dirs)

$(out)/obj/proxy/%.s : %.cpp
	@mkdir -p $(@D)
	$(CC) -S $(CC_FLAG) -o $@ $^ $(include_dirs)

